package com.android.dongshouzhi.fragment.group;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.dongshouzhi.R;
import com.android.dongshouzhi.activity.mine.LoginActivity;
import com.android.dongshouzhi.activity.mine.PaySuccessActivity1;
import com.android.dongshouzhi.adapt.GridDetaillikeAdapt;
import com.android.dongshouzhi.fragment.BaseLazyFragment;
import com.android.dongshouzhi.fragment.member.Fragment_Mine_DirectBuy_Order;
import com.android.dongshouzhi.model.MainTabData;
import com.android.dongshouzhi.model.detail.DirectBuyAliPayData;
import com.android.dongshouzhi.model.detail.DirectBuyAliPayDataCallback;
import com.android.dongshouzhi.model.detail.DirectBuyWXPayData;
import com.android.dongshouzhi.model.detail.DirectBuyWXPayDataCallback;
import com.android.dongshouzhi.model.group.FlowPaymentData;
import com.android.dongshouzhi.model.group.FlowPaymentDataCallback;
import com.android.dongshouzhi.utils.ConstantsUrl;
import com.android.dongshouzhi.utils.HttpUtils;
import com.android.dongshouzhi.utils.LoginState;
import com.android.dongshouzhi.utils.MyLog;
import com.android.dongshouzhi.utils.ObjectUtils;
import com.android.dongshouzhi.utils.ReleaseManager;
import com.android.dongshouzhi.utils.alipay.PayResult;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/9/22.
 */

public class Fragment_VoucherPay extends BaseLazyFragment {
    @BindView(R.id.voucher_img)
    ImageView voucher_img;
    @BindView(R.id.voucher_title)
    TextView voucher_title;
    @BindView(R.id.voucher_summary)
    TextView voucher_summary;
    @BindView(R.id.voucher_number)
    TextView voucher_number;
    @BindView(R.id.usetime_ll)
    LinearLayout usetime_ll;
    @BindView(R.id.foreveruse_ll)
    LinearLayout foreveruse_ll;
    @BindView(R.id.start_time)
    TextView start_time;
    @BindView(R.id.end_time)
    TextView end_time;
    @BindView(R.id.voucher_bean)
    TextView voucher_bean;
    @BindView(R.id.voucher_price2)
    TextView voucher_price2;
    @BindView(R.id.pay_style_list)
    NestFullListView pay_style_list;
    @BindView(R.id.voucher_topay)
    TextView voucher_topay;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    private FragmentActivity mcontext;
    private View view;
    private LayoutInflater inflater;
    private ArrayList<FlowPaymentData.DataBean.PaymentBean> listdata = new ArrayList<>();
    private ArrayList<MainTabData> mSortListdata = new ArrayList<>();
    private boolean networkConnected;
    private GridDetaillikeAdapt adapter;

    private  String order_sn;
    private  String pay_code;
    /** 微信注册类 */
    private String common_id = "";
    private IWXAPI iwxapi;
    private String orderInfo;
    private boolean isReallyOrder_flag;
    private static final int SDK_PAY_FLAG = 1;
    private static final String ARG_PARAM0 = "param0";
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private static final String ARG_PARAM4 = "param4";
    private static final String ARG_PARAM5 = "param5";
    private static final String ARG_PARAM6 = "param6";
    private static final String ARG_PARAM7 = "param7";
    private static final String ARG_PARAM8 = "param8";
    private static final String ARG_PARAM9 = "param9";
    private String id;
    private String singleprice = "";
    private String currentprice = "";
    private String currentnumber  = "";
    private String currentcoin  = "";
    private String currenttitle = "";
    private String currentsummary  = "";
    private String currentthumb =   "";
    private String currentstime =   "";
    private String  currentetime =   "";
    private String pay_id="";
    private String pay_name = "";
    private int pospay=100;
    public Fragment_VoucherPay() {

    }


    public static Fragment_VoucherPay newInstance(String need_id,String singleprice,String currentprice,String currentnumber,String currentcoin
            ,String currenttitle ,String currentsummary,String currentthumb,String currentstime,String currentetime) {
        Fragment_VoucherPay fragment = new Fragment_VoucherPay();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM0, need_id);
        args.putString(ARG_PARAM1, singleprice);
        args.putString(ARG_PARAM2,currentprice);
        args.putString(ARG_PARAM3, currentnumber);
        args.putString(ARG_PARAM4, currentcoin);
        args.putString(ARG_PARAM5, currentsummary);
        args.putString(ARG_PARAM6, currentthumb);
        args.putString(ARG_PARAM7,currentstime);
        args.putString(ARG_PARAM8, currentetime);
        args.putString(ARG_PARAM9, currenttitle);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getString(ARG_PARAM0);
             singleprice = getArguments().getString(ARG_PARAM1);
            currentprice = getArguments().getString(ARG_PARAM2);
            currentnumber = getArguments().getString(ARG_PARAM3);
             currentcoin = getArguments().getString(ARG_PARAM4);
             currentsummary = getArguments().getString(ARG_PARAM5);
            currentthumb = getArguments().getString(ARG_PARAM6);
            currentstime = getArguments().getString(ARG_PARAM7);
            currentetime = getArguments().getString(ARG_PARAM8);
            currenttitle = getArguments().getString(ARG_PARAM9);

        }
    }

    @Override
    protected void initPrepare() {

    }

    @Override
    protected void onInvisible() {

    }


    @Override
    protected void initData() {
        GetDataOrder();
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_voucher_pay, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        initUI();
        return view;
    }

    private void initUI() {
        ObjectUtils.photo2(mcontext,currentthumb,voucher_img);
        voucher_title.setText(currenttitle);
        voucher_summary.setText(currentsummary);
        voucher_bean.setText(currentcoin);
        voucher_number.setText("x "+currentnumber);
        voucher_price2.setText("¥ "+currentprice);
        if(currentetime.equals("0"))
        {
            foreveruse_ll.setVisibility(View.VISIBLE);
            usetime_ll.setVisibility(View.INVISIBLE);
        }
        else {
            foreveruse_ll.setVisibility(View.VISIBLE);
            usetime_ll.setVisibility(View.INVISIBLE);
            int s_time = Integer.parseInt(currentstime);
            long msl = (long) s_time * 1000;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String text = format.format(msl);
            start_time.setText(text);
            // mainlistdata.setStart_time(text);
            int e_time = Integer.parseInt(currentetime);
            long msl1 = (long) e_time * 1000;
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            String text1 = format1.format(msl1);
            end_time.setText(text1);
        }
        pay_style_list.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int position) {
               pospay = position;
                pay_id=mSortListdata.get(position).getId();
                pay_name = mSortListdata.get(position).getName();
                nestFullListView.updateUI();
            }
        });
//        mSortListdata.add(new MainTabData("微信(未开通)", "42", R.mipmap.support_pay_wx));
//        mSortListdata.add(new MainTabData("支付宝(未开通)", "", R.mipmap.support_pay_ali));
//        mSortListdata.add(new MainTabData("银联(未开通)", "", R.mipmap.support_pay_yl));



    }


    @OnClick({R.id.voucher_topay,R.id.choose_again
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.choose_again:
                mcontext.finish();
                break;
            case R.id.voucher_topay:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    toPay();
                }
                else
                {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;

        }
    }
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(mcontext, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent mIntent = new Intent(Fragment_Mine_DirectBuy_Order.DIRECTBUY_ORDER_PAY);
                        mcontext.sendBroadcast(mIntent);
                        toPaySuccess();
                        getActivity().finish();
                    } else {
                        if (TextUtils.equals(resultStatus, "8000") || TextUtils.equals(resultStatus, "6004")) {
                            ObjectUtils.toast(mcontext, "支付结果确认中");
                        }
                        else if (TextUtils.equals(resultStatus, "6001")) {
                            ObjectUtils.toast(mcontext, "支付取消");
//                            toPaySuccess();
//                            finish();
                        }
                        else if (TextUtils.equals(resultStatus, "6002")) {
                            ObjectUtils.toast(mcontext, "网络异常");
                        }
                        else if (TextUtils.equals(resultStatus, "5000")) {
                            ObjectUtils.toast(mcontext, "重复请求");
                        }
                        else {
                            // 其他值就可以判断为支付失败
                            ObjectUtils.toast(mcontext, "支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };
    private void toPaySuccess() {
        Intent intent = new Intent(getActivity(), PaySuccessActivity1.class);
        startActivity(intent);
    }
    private void toPay() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.VOUCHERCHECKOUT;
        HashMap<String, String> map = new HashMap<>();
        MyLog.e("1",pay_id);
        MyLog.e("2",id);
        MyLog.e("3",currentnumber);
        map.put("pay_id", pay_id + "");
        map.put("id", id );
        map.put("count",currentnumber);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            MyLog.e("pay_name",pay_name);
            if (pay_name.equals("微信")) {
                HttpUtils.post(address, header, map, wxPayDataCallback);
            } else if(pay_name.equals("支付宝")) {
                HttpUtils.post(address, header, map, aliPayDataCallback);
            }
            else{
                ObjectUtils.toast(mcontext, "请选择支付方式");
            }
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            //ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    DirectBuyWXPayDataCallback wxPayDataCallback = new DirectBuyWXPayDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }

        @Override
        public void onResponse(DirectBuyWXPayData response, int id) {
            if(response.getData()!=null&&response.getData().getPaycode()!=null&&response.getData().getPaycode().getAppid()!=null){
                ReleaseManager.printLog("DirectBuyWXPayData","微信支付发起");
                //微信支付发起
                IWXAPI iwxapi = WXAPIFactory.createWXAPI(mcontext, ConstantsUrl.WX_APPID, true);
                iwxapi.registerApp(ConstantsUrl.WX_APPID);
                PayReq req = new PayReq();
                req.appId = ConstantsUrl.WX_APPID;
                req.partnerId = response.getData().getPaycode().getPartnerid();
                req.prepayId = response.getData().getPaycode().getPrepayid();
                req.packageValue = response.getData().getPaycode().getWxpackage();
                req.nonceStr = response.getData().getPaycode().getNoncestr();
                req.timeStamp = response.getData().getPaycode().getTimestamp()+"";
                req.sign = response.getData().getPaycode().getSign();
                iwxapi.sendReq(req);
            }
        }
    };

    DirectBuyAliPayDataCallback aliPayDataCallback = new DirectBuyAliPayDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }

        @Override
        public void onResponse(DirectBuyAliPayData response, int id) {
            if (response.getData() != null && response.getData().getPaycode() != null) {
                final String orderInfo = response.getData().getPaycode();
                //支付宝支付发起
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(mcontext);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else {
                ObjectUtils.toast(mcontext, response.getMsg());
            }
        }
    };

    //网络数据
    private void GetDataOrder() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.FLOWPAYMENT ;

        MyLog.e("地址", address);
        if (networkConnected) {
            HttpUtils.get(address,  null, new FlowPaymentDataCallback() {


                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.toast(mcontext, "没有获取到支付方式");
                }

                @Override
                public void onResponse(FlowPaymentData response, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0 && response.getData() != null) {
                       listdata.addAll(response.getData().getPayment());
                        //支付方式
                        mSortListdata.clear();
                            for (int i = 0; i < listdata.size(); i++) {
                                String  pay_id = listdata.get(i).getPay_id() ;
                                if (listdata.get(i).getPay_code().equals("wxpayapp")) {
                                    mSortListdata.add(new MainTabData("微信",pay_id , R.mipmap.support_pay_wx));
                                }
                                if (listdata.get(i).getPay_code().equals("alipayapp")) {
                                    mSortListdata.add(new MainTabData("支付宝", pay_id , R.mipmap.support_pay_ali));
                                }
                            }
                        if(listdata.size()>0) {
                            pay_id = listdata.get(0).getPay_id();
                        }

                        //        mSortListdata.add(new MainTabData("银联(未开通)", "", R.mipmap.support_pay_yl));
                        pay_style_list.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_pay, mSortListdata) {
                            @Override
                            public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                                holder.setText(R.id.pay_name, testBean.getName());
                                holder.setImageResource(R.id.pay_logo, testBean.getThumb());
                                if (pospay == position) {//最后选择的位置
                                    holder.setChecked(R.id.item_list_mine_pay_check, true);
                                } else {
                                    holder.setChecked(R.id.item_list_mine_pay_check, false);
                                }
                            }
                        });
                        pay_style_list.updateUI();
                    } else {
                        ObjectUtils.toast(mcontext, "没有获取到支付方式");
                    }


                }
            });
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }





}
